<template>
  <div class="register-container">
    <!-- 背景动画 -->
    <canvas id="register-bg" class="register-bg"></canvas>

    <!-- 背景渐变层 -->
    <div class="bg-overlay"></div>

    <!-- 装饰元素 -->
    <div class="decoration">
      <div class="palm-tree"></div>
      <div class="sun"></div>
    </div>

    <!-- 注册框 -->
    <div class="register-box">
      <div class="register-content">
        <h2 class="title">创建账号</h2>
        <p class="subtitle">加入我们的心理咨询平台</p>

        <el-form 
          ref="registerFormRef" 
          :model="registerForm" 
          :rules="registerRules" 
          class="register-form"
          label-position="top"
        >
          <!-- 基本信息部分 -->
          <el-form-item prop="username" required>
            <el-input 
              v-model="registerForm.username"
              placeholder="用户名"
              :prefix-icon="User"
            />
          </el-form-item>
          
          <el-form-item prop="password" required>
            <el-input
              v-model="registerForm.password"
              type="password"
              placeholder="密码"
              :prefix-icon="Lock"
              show-password
              @input="checkPasswordStrength"
            />
            <!-- 密码强度提示 -->
            <div class="password-strength" v-if="registerForm.password">
              <div class="strength-label">密码强度：</div>
              <div class="strength-bars">
                <div class="bar" :class="{ active: passwordStrength >= 1 }"></div>
                <div class="bar" :class="{ active: passwordStrength >= 2 }"></div>
                <div class="bar" :class="{ active: passwordStrength >= 3 }"></div>
              </div>
              <span class="strength-text" :class="strengthClass">{{ strengthText }}</span>
            </div>
          </el-form-item>

          <el-form-item prop="confirmPassword" required>
            <el-input
              v-model="registerForm.confirmPassword"
              type="password"
              placeholder="确认密码"
              :prefix-icon="Lock"
              show-password
            />
          </el-form-item>

          <el-form-item prop="realName" required>
            <el-input
              v-model="registerForm.realName"
              placeholder="真实姓名"
              :prefix-icon="UserFilled"
            />
          </el-form-item>

          <el-form-item prop="phone" required>
            <el-input
              v-model="registerForm.phone"
              placeholder="手机号"
              :prefix-icon="Phone"
            />
          </el-form-item>

          <el-form-item prop="email" required>
            <el-input
              v-model="registerForm.email"
              placeholder="邮箱"
              :prefix-icon="Message"
            />
          </el-form-item>

          <el-form-item prop="role" class="role-select" required>
            <el-radio-group v-model="registerForm.role">
              <el-radio-button label="student">学生</el-radio-button>
              <el-radio-button label="counselor">心理咨询师</el-radio-button>
            </el-radio-group>
          </el-form-item>

          <!-- 咨询师信息部分 -->
          <template v-if="registerForm.role === 'counselor'">
            <div class="counselor-info">
              <el-divider>咨询师信息</el-divider>
              
              <el-row :gutter="24">
                <el-col :span="12">
                  <el-form-item label="职称" prop="title" required>
                    <el-input 
                      v-model="registerForm.title" 
                      placeholder="请输入职称"
                    />
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="从业年限" prop="workYears" required>
                    <el-input-number 
                      v-model="registerForm.workYears" 
                      :min="0" 
                      :max="100"
                      controls-position="right"
                      style="width: 100%"
                      placeholder="请输入从业年限"
                    />
                  </el-form-item>
                </el-col>
              </el-row>

              <el-form-item label="专长领域" prop="specialty" required>
                <el-select
                  v-model="registerForm.specialty"
                  multiple
                  filterable
                  allow-create
                  default-first-option
                  placeholder="请选择专长领域"
                  style="width: 100%"
                >
                  <el-option
                    v-for="item in specialtyOptions"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-select>
              </el-form-item>

              <el-form-item label="资质证书" prop="qualification" required>
                <el-input 
                  v-model="registerForm.qualification" 
                  placeholder="请输入资质证书名称，如：国家二级心理咨询师"
                />
              </el-form-item>

              <el-form-item label="证书编号" prop="certificateNo" required>
                <el-input 
                  v-model="registerForm.certificateNo" 
                  placeholder="请输入证书编号"
                />
              </el-form-item>

              <el-form-item label="证书文件" prop="certificateUrl" required>
                <div class="upload-box">
                  <el-upload
                    class="upload-certificate"
                    action="/api/certificate"
                    :on-success="handleUploadSuccess"
                    :on-error="handleUploadError"
                    :before-upload="beforeUpload"
                    :on-preview="handlePreview"
                    accept=".jpg,.jpeg,.png,.pdf"
                    :file-list="fileList"
                  >
                    <el-button type="primary" :icon="Upload">
                      上传证书
                    </el-button>
                    <div class="upload-tip">
                      支持jpg/jpeg/png/pdf格式，不超过10MB
                    </div>
                  </el-upload>
                </div>
              </el-form-item>

              <el-form-item label="个人介绍" prop="introduction" required>
                <el-input 
                  v-model="registerForm.introduction" 
                  type="textarea" 
                  :rows="4"
                  placeholder="请简要介绍您的教育背景、工作经历、专业特长等"
                />
              </el-form-item>
            </div>
          </template>

          <el-form-item>
            <el-button 
              type="primary" 
              class="submit-btn"
              :loading="loading"
              @click="handleRegister"
            >
              注册
            </el-button>
          </el-form-item>

          <div class="form-footer">
            <span>已有账号？</span>
            <el-link type="primary" :underline="false" @click="router.push('/login')">
              返回登录
            </el-link>
          </div>
        </el-form>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive } from 'vue'
import { useRouter } from 'vue-router'
import { useStore } from 'vuex'
import { ElMessage } from 'element-plus'
import { User, Lock, UserFilled, Phone, Message, Upload } from '@element-plus/icons-vue'
import { initParticles } from '@/utils/particles'
import { onMounted, onUnmounted } from 'vue'
import { RegisterForm } from '@/types/user'

const router = useRouter()
const store = useStore()

// 注册表单验证规则
const registerRules = reactive({
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, message: '密码长度不能小于6位', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请确认密码', trigger: 'blur' },
    {
      validator: (rule: any, value: string, callback: Function) => {
        if (value !== registerForm.password) {
          callback(new Error('两次输入的密码不一致'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ],
  realName: [
    { required: true, message: '请输入真实姓名', trigger: 'blur' }
  ],
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
  ],
  role: [
    { required: true, message: '请选择角色', trigger: 'change' }
  ],
  // 咨询师特有字段的验证规则
  title: [
    { required: true, message: '请输入职称', trigger: 'blur' }
  ],
  specialty: [
    { required: true, message: '请选择专长领域', trigger: 'blur' },
    { type: 'array', min: 1, message: '请至少选择一个专长领域', trigger: 'change' }
  ],
  qualification: [
    { required: true, message: '请输入资质证书', trigger: 'blur' }
  ],
  workYears: [
    { required: true, message: '请输入从业年限', trigger: 'blur' },
    { 
      validator: (rule: any, value: number, callback: Function) => {
        if (value === undefined || value === null) {
          callback(new Error('请输入从业年限'))
        } else if (value <= 0) {
          callback(new Error('从业年限必须大于0年'))
        } else if (value > 50) {
          callback(new Error('从业年限不能超过50年'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ],
  introduction: [
    { required: true, message: '请输入个人介绍', trigger: 'blur' },
    { min: 10, message: '个人介绍不能少于10个字', trigger: 'blur' }
  ],
  certificateNo: [
    { required: true, message: '请输入证书编号', trigger: 'blur' }
  ],
  certificateUrl: [
    { required: true, message: '请上传证书文件', trigger: 'change' }
  ]
})

// 表单数据
const registerForm = reactive<RegisterForm>({
  username: '',
  password: '',
  confirmPassword: '',
  realName: '',
  phone: '',
  email: '',
  role: 'student',
  status: '',
  // 咨询师特有字段
  title: '',
  specialty: [],
  qualification: '',
  workYears: 0,
  introduction: '',
  certificateNo: '',
  certificateUrl: ''
})

// 密码强度相关
const passwordStrength = ref(0)
const strengthText = ref('')
const strengthClass = ref('')

// 检查密码强度
const checkPasswordStrength = (password: string) => {
  let strength = 0
  
  if (password.length >= 8) strength++
  if (/[A-Z]/.test(password)) strength++
  if (/[0-9]/.test(password)) strength++
  if (/[^A-Za-z0-9]/.test(password)) strength++

  passwordStrength.value = strength
  
  switch (strength) {
    case 0:
    case 1:
      strengthText.value = '弱'
      strengthClass.value = 'weak'
      break
    case 2:
      strengthText.value = '中'
      strengthClass.value = 'medium'
      break
    case 3:
      strengthText.value = '强'
      strengthClass.value = 'strong'
      break
    case 4:
      strengthText.value = '非常强'
      strengthClass.value = 'very-strong'
      break
  }
}

const loading = ref(false)
const registerFormRef = ref()

// 添加文件列表响应式变量
const fileList = ref<any[]>([])

// 上传前验证
const beforeUpload = (file: File) => {
  const isValidType = ['image/jpeg', 'image/png', 'application/pdf'].includes(file.type)
  const isLt10M = file.size / 1024 / 1024 < 10

  if (!isValidType) {
    ElMessage.error('只能上传jpg/jpeg/png/pdf格式的文件!')
    return false
  }
  if (!isLt10M) {
    ElMessage.error('文件大小不能超过10MB!')
    return false
  }
  return true
}

// 上传成功
const handleUploadSuccess = (response: any, file: any) => {
  if (response.code === 200) {
    registerForm.certificateUrl = response.data
    fileList.value = [{ name: file.name, url: response.data }]
    ElMessage.success('证书上传成功')
  } else {
    ElMessage.error(response.message || '证书上传失败')
  }
}

// 上传失败
const handleUploadError = () => {
  ElMessage.error('证书上传失败')
}

// 文件预览
const handlePreview = (file: any) => {
  window.open(file.url, '_blank')
}

const handleRegister = async () => {
  if (!registerFormRef.value) return
  
  try {
    await registerFormRef.value.validate()
    loading.value = true
    
    // 创建基础数据对象
    const baseData = {
      username: registerForm.username,
      password: registerForm.password,
      realName: registerForm.realName,
      phone: registerForm.phone,
      email: registerForm.email,
      role: registerForm.role,
      status: registerForm.role === 'counselor' ? 'PENDING' : 'ACTIVE'
    }
    
    // 如果是咨询师，添加咨询师特有字段
    const submitData = registerForm.role === 'counselor' 
      ? Object.assign({}, baseData, {
          title: registerForm.title,
          specialty: registerForm.specialty,
          qualification: registerForm.qualification,
          workYears: registerForm.workYears,
          introduction: registerForm.introduction,
          certificateNo: registerForm.certificateNo,
          certificateUrl: registerForm.certificateUrl
        })
      : baseData
    
    await store.dispatch('user/register', submitData)
    ElMessage.success(
      registerForm.role === 'counselor' 
        ? '注册申请已提交，请等待管理员审核' 
        : '注册成功'
    )
    router.push('/login')
    
  } catch (error: any) {

  } finally {
    loading.value = false
  }
}

// 初始化粒子效果
onMounted(() => {
  const cleanup = initParticles('register-bg')
  onUnmounted(() => {
    if (cleanup) cleanup()
  })
})

// 添加专长领域选项
const specialtyOptions = [
  { value: '心理咨询', label: '心理咨询' },
  { value: '职业规划', label: '职业规划' },
  { value: '情感咨询', label: '情感咨询' },
  { value: '学业问题', label: '学业问题' },
  { value: '人际关系', label: '人际关系' },
  { value: '家庭问题', label: '家庭问题' },
  { value: '压力管理', label: '压力管理' },
  { value: '自我认知', label: '自我认知' }
]
</script>

<style lang="scss" scoped>
.register-container {
  min-height: 100vh;
  display: flex;
  align-items: center;
  justify-content: center;
  background: linear-gradient(135deg, #ff9a9e 0%, #fad0c4 99%, #fad0c4 100%);
  position: relative;
  overflow: hidden;

  .bg-overlay {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background: linear-gradient(
      to bottom,
      rgba(255, 183, 77, 0.2) 0%,
      rgba(255, 167, 77, 0.3) 50%,
      rgba(255, 152, 77, 0.4) 100%
    );
    z-index: 1;
  }

  .decoration {
    position: fixed;
    width: 100%;
    height: 100%;
    z-index: 0;
    pointer-events: none;

    .sun {
      position: absolute;
      top: 15%;
      right: 10%;
      width: 100px;
      height: 100px;
      background: radial-gradient(
        circle at center,
        #ffd700 0%,
        #ff8c00 60%,
        transparent 100%
      );
      border-radius: 50%;
      opacity: 0.8;
      animation: glow 3s infinite alternate;
    }

    .palm-tree {
      position: absolute;
      bottom: 0;
      left: 5%;
      width: 200px;
      height: 300px;
      background-image: url('@/assets/palm-tree.png');
      background-size: contain;
      background-repeat: no-repeat;
      background-position: bottom;
      opacity: 0.8;
      transform-origin: bottom;
      animation: sway 5s ease-in-out infinite;
    }
  }

  .register-bg {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    z-index: 2;
  }

  .register-box {
    position: relative;
    z-index: 3;
    width: 400px;
    padding: 40px;
    background: rgba(255, 255, 255, 0.85);
    border-radius: 16px;
    box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
    backdrop-filter: blur(10px);
    animation: slideIn 0.6s ease;

    .register-content {
      .title {
        font-size: 28px;
        font-weight: 600;
        text-align: center;
        margin-bottom: 8px;
        background: linear-gradient(45deg, #ff8c00, #ff6b6b);
        -webkit-background-clip: text;
        background-clip: text;
        color: transparent;
      }

      .subtitle {
        text-align: center;
        color: #666;
        margin-bottom: 32px;
      }

      .register-form {
        .el-input {
          --el-input-hover-border-color: #ff8c00;
          --el-input-focus-border-color: #ff8c00;
        }

        .submit-btn {
          width: 100%;
          height: 44px;
          margin-top: 20px;
          font-size: 16px;
          background: linear-gradient(45deg, #ff8c00, #ff6b6b);
          border: none;
          transition: all 0.3s;

          &:hover {
            transform: translateY(-2px);
            box-shadow: 0 5px 15px rgba(255, 107, 107, 0.4);
          }
        }

        .form-footer {
          margin-top: 24px;
          text-align: center;
          color: #666;
          display: flex;
          align-items: center;
          justify-content: center;
          gap: 4px;
          font-size: 14px;

          :deep(.el-link) {
            margin: 0;
            height: auto;
            line-height: 1;
            font-size: 14px;
          }
        }

        .counselor-fields {
          margin-top: 16px;
          padding: 16px;
          background: #f8f9fa;
          border-radius: 4px;

          .field-title {
            font-size: 14px;
            color: #666;
            margin-bottom: 16px;
          }
        }

        .certificate-uploader {
          .el-upload {
            width: 100%;
            
            .el-button {
              width: 100%;
            }
          }

          .el-upload__tip {
            color: #666;
            font-size: 12px;
            margin-top: 4px;
          }
        }
      }

      .upload-wrapper {
        display: flex;
        align-items: center;
        gap: 10px;

        .certificate-upload {
          :deep(.el-upload) {
            width: auto;
          }

          :deep(.el-upload__tip) {
            margin: 0;
            margin-left: 10px;
            line-height: 32px;
            color: #909399;
          }
        }
      }

      // 调整表单项间距
      :deep(.el-form-item) {
        margin-bottom: 20px;

        &.is-required .el-form-item__label::before {
          margin-right: 2px;
        }

        .el-form-item__label {
          font-weight: 500;
        }
      }

      // 调整输入框样式
      :deep(.el-input),
      :deep(.el-textarea) {
        .el-input__wrapper,
        .el-textarea__inner {
          box-shadow: 0 0 0 1px #dcdfe6 inset;
          
          &:hover {
            box-shadow: 0 0 0 1px #c0c4cc inset;
          }
          
          &.is-focus {
            box-shadow: 0 0 0 1px #409eff inset;
          }
        }
      }

      // 调整数字输入框样式
      :deep(.el-input-number) {
        width: 100%;
        
        .el-input__wrapper {
          padding-left: 0;
          padding-right: 0;
        }
      }

      // 分割线样式
      :deep(.el-divider) {
        margin: 24px 0;
        
        .el-divider__text {
          font-size: 16px;
          font-weight: 500;
          color: #303133;
        }
      }
    }
  }
}

@keyframes glow {
  from {
    box-shadow: 0 0 20px #ffd700;
  }
  to {
    box-shadow: 0 0 40px #ff8c00;
  }
}

@keyframes sway {
  0%, 100% {
    transform: rotate(-2deg);
  }
  50% {
    transform: rotate(2deg);
  }
}

@keyframes slideIn {
  from {
    opacity: 0;
    transform: translateY(20px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

// 响应式调整
@media (max-width: 480px) {
  .register-container {
    .register-box {
      width: 90%;
      margin: 0 20px;
      padding: 30px 20px;
    }
  }
}

// 密码强度样式
.password-strength {
  margin-top: 5px;
  display: flex;
  align-items: center;
  font-size: 12px;

  .strength-label {
    margin-right: 8px;
    color: #666;
  }

  .strength-bars {
    display: flex;
    gap: 4px;
    margin-right: 8px;

    .bar {
      width: 20px;
      height: 4px;
      background: #ddd;
      border-radius: 2px;

      &.active {
        &:nth-child(1) { background: #ff4757; }
        &:nth-child(2) { background: #ffa502; }
        &:nth-child(3) { background: #2ed573; }
      }
    }
  }

  .strength-text {
    &.weak { color: #ff4757; }
    &.medium { color: #ffa502; }
    &.strong { color: #2ed573; }
    &.very-strong { color: #2ed573; }
  }
}

.login-link {
  text-align: center;
  color: #666;
  font-size: 14px;
  margin-top: 16px;
  
  .el-link {
    margin-left: 5px;
    font-size: 14px;
  }

  :deep(.el-link:hover) {
    color: var(--el-color-primary);  // 只改变颜色，不显示下划线
  }
}

.certificate-uploader {
  .el-upload__tip {
    color: #666;
    font-size: 12px;
    margin-top: 4px;
  }
}

:deep(.el-input-number) {
  width: 100%;
  
  .el-input__wrapper {
    padding-left: 11px;
  }
}

.role-select {
  margin: 24px 0;
  :deep(.el-radio-group) {
    width: 100%;
    display: flex;
    gap: 12px;
    
    .el-radio-button {
      flex: 1;
      
      .el-radio-button__inner {
        width: 100%;
      }
    }
  }
}

.counselor-info {
  background: #f8f9fa;
  border-radius: 8px;
  padding: 20px;
  margin-bottom: 24px;

  :deep(.el-divider) {
    margin: 0 0 20px;
    
    .el-divider__text {
      font-size: 16px;
      font-weight: 500;
      background: #f8f9fa;
      padding: 0 20px;
    }
  }

  .upload-box {
    display: flex;
    align-items: center;
    gap: 12px;

    .certificate-upload {
      :deep(.el-upload) {
        display: block;
      }
    }

    .upload-tip {
      color: #909399;
      font-size: 12px;
    }
  }

  .uploaded-file {
    margin-top: 8px;
    
    .el-tag {
      display: inline-flex;
      align-items: center;
      max-width: 100%;
      
      .el-tag__content {
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
      }
    }
  }
}

:deep(.el-form-item) {
  margin-bottom: 20px;

  .el-form-item__label {
    padding-bottom: 8px;
    font-weight: 500;
    color: #333;
  }

  .el-form-item__content {
    line-height: 1;
  }
}

:deep(.el-input),
:deep(.el-textarea) {
  .el-input__wrapper,
  .el-textarea__inner {
    box-shadow: 0 0 0 1px #dcdfe6 inset;
    
    &:hover {
      box-shadow: 0 0 0 1px #c0c4cc inset;
    }
    
    &.is-focus {
      box-shadow: 0 0 0 1px #409eff inset;
    }
  }
}

:deep(.el-input-number) {
  width: 100%;
  
  .el-input__wrapper {
    padding: 1px 11px;
  }
}

.submit-btn {
  width: 100%;
  margin-top: 24px;
  height: 40px;
  font-size: 16px;
}

.form-footer {
  margin-top: 16px;
  text-align: center;
  color: #606266;

  .el-link {
    margin-left: 8px;
    font-weight: 500;
  }
}

.upload-box {
  .upload-certificate {
    :deep(.el-upload-list) {
      margin-top: 8px;
    }
    
    :deep(.el-upload-list__item) {
      margin: 0;
      padding: 0;
      height: auto;
      
      .el-upload-list__item-name {
        padding: 0 30px 0 20px;
        line-height: 1.5;
        white-space: normal;
        word-break: break-all;
      }

      // 隐藏删除提示文本
      .el-icon--close-tip {
        display: none !important;
      }
    }
  }

  .upload-tip {
    margin-top: 8px;
    color: #909399;
    font-size: 12px;
  }
}
</style>
